import { expect } from '@jest/globals';
import { iconv } from '@ohos/hvigor';
import * as execa from 'execa';
import fse from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { commonConfig } from '../../plugins/common-config';
import { commonFileOperation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { Project } from '../../plugins/project-builder/models/project-models';
import { ICaseRecord } from '../../plugins/report-builder/report-models';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.NativeC,
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibraryWithC]: 2
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.Enable,
};

/**
 * mark构建并将产物复制到目标文件目录
 * @param project Project
 * @param record Record
 * @param library library
 * @param target 目标目录
 */
async function copyHar(project: Project, record: ICaseRecord, library: string, target: string) {
  const projectRootPath = project.projectRootPath();

  const commandObj = {
    mode: 'module',
    product: 'default',
    tasks: 'assembleHar'
  };

  const libraryCommand = initExecuteCommand({...commandObj, module: library});
  const result = await runHvigorAsync(projectRootPath, libraryCommand);
  record.addStep(`build ${library}模块`, result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 将生成的har包复制到目标
  const harPath = path.resolve(projectRootPath, `${library}/build/default/outputs/default/${library}.har`);
  await fse.copyFile(harPath, path.resolve(projectRootPath, `${target}/${library}.har`));

  // 添加依赖
  const libraryPath = path.resolve(projectRootPath, `${target}/oh-package.json5`);
  const jsonBuffer = await fse.readFile(libraryPath);
  const packageObj = JSON.parse(iconv.decode(jsonBuffer, 'utf-8'));


  // packageObj.dependencies[library] = `file:./${library}.har`;
  // 该版本未支持间接har依赖，先使用模块依赖
  // 5.0.3.420
  packageObj.dependencies[library] = `file:../${library}`;
  await fse.writeFile(libraryPath, JSON.stringify(packageObj, null, 2), 'utf-8');

  // 执行ohpm install
  await execa.command(commonConfig.ohpmInstallCommand, {
    cwd: path.resolve(project.getModule(target).moduleRootPath())
  });
}

async function addTestString(projectRootPath: string, dir:string) {
  const libraryString = `staticNativeCLibrary1/src/main/resources/${dir}/element/string.json`;
  const stringPath = path.resolve(projectRootPath, libraryString);
  const stringBuffer: Buffer = await fse.readFile(stringPath);
  const stringObj = JSON.parse(iconv.decode(stringBuffer, 'utf-8'));
  stringObj.string.push({name: 'test', value: 'hello'});
  await fse.writeFile(stringPath, JSON.stringify(stringObj, null, 2), 'utf-8');
}

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const command = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHar'
  });

  // 2、在library1下添加一个string，例如：{"name"："test"，"value"："hello"};
  const jsonAirs = ['base', 'en_US', 'zh_CN'];
  for (const dir of jsonAirs) {
    await addTestString(projectRootPath, dir);
  }

  // 打包library1,将library1.har复制到library，并添加依赖
  await copyHar(project, record, 'staticNativeCLibrary1', 'staticNativeCLibrary');

  // 打包library,将library.har复制到entry，并添加依赖
  await copyHar(project, record, 'staticNativeCLibrary', 'entry');
  const pagePath = path.resolve(projectRootPath, 'entry/src/main/ets/pages/Index.ets');
  await commonFileOperation(pagePath, async (buffer) => {
    let content = buffer.toString();
    content = content.replace('this.message', '$r(\'app.string.test\')');
    return content;
  });

  const result = await runHvigorAsync(projectRootPath, command);
  record.addStep('执行 assembleHar 任务', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_Transitive_Dependency_Stage_HOS_api10_STAGE_01')
  .description('01、新模型entry依赖library-library依赖library1')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();